<template>
    <ElDialog
        v-model.sync="dialogVisible"
        :class="{ animated: true, fadeOutDown: !dialogVisible, fadeInDown: dialogVisible }"
        width="640px"
        :title="title"
        :closeOnClickModal="false"
        :modalAppendToBody="false"
        @open="openInit"
        @close="close"
        draggable
    >
        <el-form
            ref="formRef"
            :model="form"
            v-loading="loading"
            labelWidth="120px"
            labelPosition="right"
            labelSuffix=":"
        >
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item
                        label="科目类型"
                        prop="subjectType"
                        :rules="[{ required: true, message: '请选择科目类型', trigger: 'change' }]"
                    >
                        <el-select
                            v-model="form.subjectType"
                            style="width: 100%"
                            placeholder="请选择科目类型"
                            @change="subjectTypeChange"
                        >
                            <el-option label="收入" value="1" />
                            <el-option label="外包费用" value="2" />
                            <el-option label="期间费用" value="3" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item
                        label="会计科目编码"
                        prop="subjectCode"
                        :rules="[{ required: true, message: '请选择会计科目编码', trigger: 'change' }]"
                    >
                        <el-select
                            v-model="form.subjectCode"
                            style="width: 100%"
                            placeholder="请选择会计科目编码"
                            filterable
                            @change="subjectCodeChange"
                        >
                            <el-option
                                v-for="item in subjectOpts"
                                :key="item.subjectCode"
                                :label="item.subjectName + ' 【' + item.subjectCode + '】'"
                                :value="item.subjectCode"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item
                        label="opro系统编码"
                        prop="oproCode"
                        :rules="[{ required: true, message: '请选择opro系统编码', trigger: 'change' }]"
                    >
                        <el-select
                            v-model="form.oproCode"
                            style="width: 100%"
                            placeholder="请选择opro系统编码"
                            filterable
                            @change="oproCodeChange"
                        >
                            <el-option
                                v-for="item in systemCodeList"
                                :key="item.value"
                                :label="item.label + ' 【' + item.value + '】'"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <ElButton type="primary" @click="submitPartForm">确 定</ElButton>
                <ElButton @click="handleCancel">取 消</ElButton>
            </div>
        </template>
    </ElDialog>
</template>

<script setup name="BiddingAddEdit">
import { erpReflectAdd, erpReflectUpdate, erpSubjectList } from '@/api/project/erpReflect';
import useDictStore from '@/store/modules/dict';

const { proxy } = getCurrentInstance();
const emit = defineEmits(['refresh']);

proxy.useDict('pro_income_type', 'pro_outcome_package', 'pro_outcome_period');

const formRef = ref(null);
const form = reactive({
    id: null,
    subjectCode: '', // 会计科目编码
    subjectName: '', // 会计科目名称，物业管理费
    parentCode: '', // 父会计科目code, 2020.11
    parentName: '', // 父会计科目名称
    subjectType: '1', // 科目类型，1收入，2外包费用，3期间费用
    oproCode: '', // opro系统对应的编码，704
    oproName: '', // opro系统对应的名称
});

const rowId = ref(null);
const isAdd = ref(true);
const isEdit = ref(false);
const title = computed(() => (isAdd.value ? '新增编码映射' : '编辑编码映射'));
const dialogVisible = ref(false);
const loading = ref(false);

// 获取会计(ERP)科目编码
const subjectOpts = ref([]);
const getSubjectOpts = async () => {
    const result = await erpSubjectList().then(res => res.rows);
    if (result) {
        subjectOpts.value = result;
    }
};

function subjectTypeChange(val) {
    getDictOpt(val);
}

function resetForm() {
    formRef.value?.resetFields();
    form.detailList = [];
}

function handleCancel() {
    dialogVisible.value = false;
    resetForm();
}

function close() {
    dialogVisible.value = false;
    resetForm();
}

function submitPartForm() {
    formRef.value?.validate(valid => {
        if (valid) {
            // 验证通过，提交表单
            if (isAdd.value) addSubmit();
            if (isEdit.value) editSubmit();
        } else {
            // 验证不通过，提示错误信息
            console.log('error submit!!');
            return false;
        }
    });
}

function addSubmit(params) {
    form.id = null;
    erpReflectAdd(form).then(res => {
        if (res.code === 200) {
            proxy.$modal.msgSuccess('操作成功');
            close();
            emit('refresh');
        }
    });
}

function editSubmit(params) {
    erpReflectUpdate(form).then(res => {
        if (res.code === 200) {
            proxy.$modal.msgSuccess('操作成功');
            close();
            emit('refresh');
        }
    });
}

const systemCodeList = ref([]);
async function getDictOpt(code) {
    let str = '';
    if (code === 'pro_income_type' || code == 1) {
        str = 'pro_income_type';
    }
    if (code === 'pro_outcome_package' || code == 2) {
        str = 'pro_outcome_package';
    }
    if (code === 'pro_outcome_period' || code == 3) {
        str = 'pro_outcome_period';
    }
    systemCodeList.value = useDictStore()
        .getDict(str)
        .filter(item => item.label.indexOf('停用') === -1);
}

function subjectCodeChange(val) {
    const selectedItem = subjectOpts.value.find(item => item.subjectCode == val);
    form.subjectName = selectedItem.subjectName;
    form.parentCode = selectedItem.parentCode;
    form.parentName = selectedItem.parentName;
}

function oproCodeChange(val) {
    const selectedItem = systemCodeList.value.find(item => item.value == val);
    form.oproName = selectedItem.label;
}

// 反向触发 弹框的open事件
function openInit(params) {
    getSubjectOpts();
    if (isEdit.value) {
        getDictOpt(form.subjectCode);
    } else {
        getDictOpt('pro_income_type');
    }
}

const open = row => {
    isAdd.value = !row;
    isEdit.value = !!row;
    dialogVisible.value = true;
    if (isEdit.value) {
        rowId.value = row.id;
        form.id = row.id;
        form.subjectCode = row.subjectCode;
        form.subjectName = row.subjectName;
        form.parentCode = row.parentCode;
        form.parentName = row.parentName;
        form.subjectType = row.subjectType;
        form.oproCode = row.oproCode;
        form.oproName = row.oproName;
    }

    console.log("form", form)
};

defineExpose({
    open,
});
</script>

<style lang="scss" scoped>
.title {
    line-height: 24px;
    font-weight: bold;
    border-bottom: 1px solid #ddd;
    padding-top: 10px;
    margin-bottom: 10px;
}

::v-deep(.el-descriptions__label) {
    width: 110px;
}

::v-deep(.detail-img #upload) {
    display: none;
}

.form-layout {
    margin-top: 20px;
}

.form-title {
    margin-left: 4px;
    font-size: 16px;
    padding-bottom: 14px;
}
.section-title {
    margin-left: 4px;
    font-size: 16px;
    padding-bottom: 14px;
    border-bottom: 1px solid #ddd;
    margin-bottom: 20px;
    padding-left: 4px;
    position: relative;
}
.section-title::after {
    content: '';
    position: absolute;
    width: 6px;
    height: 20px;
    background-color: #409eff;
    left: -10px;
    top: 2px;
}
.add-btn {
    padding-bottom: 14px;
}
</style>
